package com.bigdata.collector.stork;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import com.bigdata.collector.model.Page;
import com.bigdata.collector.util.HttpUtils;
import com.bigdata.collector.util.PinyinUtil;

public class SinaStork {

	public static void main(String[] args) {
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("javascript");
		try {
			for (int i = 0; i < 500; i++) {
				String subCode = i + "";
				StringBuffer sb = new StringBuffer("300000");
				String code = sb.replace(6 - subCode.length(), sb.length(), subCode).toString();
				System.out.println(code);
				String url = "http://hq.sinajs.cn/list=sz" + code;
				Page page = HttpUtils.fetchHttpResponse(url);
				engine.eval(new String(page.content, "gbk")
						+ ";var elements=hq_str_sz" + code
						+ ".split(\",\");var result = elements[0];");
				String result = (String) engine.get("result");
				if (result != null && !result.equals("")) {
					write2SqlFile(result, code + "", PinyinUtil
							.getPinYinHeadChar(result).toLowerCase(), true);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void write2SqlFile(String name, String code,
			String firstletter, boolean appender) {
		try {
			FileOutputStream fos = new FileOutputStream("store/stork.sql",
					appender);
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
			String sql = "INSERT IGNORE INTO `fe_subscribe_stork`(keyword,firstletter,CODE) VALUE('"
					+ name + "','" + firstletter + "','" + code + "');\n";
			bw.write(sql);
			bw.close();
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
